/**
 *
 * Copyright (C) 2013 陕西威尔伯乐信息技术有限公司
 *
 * @className:com.wellbole.sms.client.service.SmsFetcherThreadService
 * @description: 短信接受线程服务，该服务定期主动获取上行短信，并回调客户提供的回调接口进行短信处理
 *
 * @version:v1.0.0
 * @author:李飞
 *
 * Modification History:
 * Date         Author      Version     Description
 * -----------------------------------------------------------------
 * 2013年7月1日      李飞                       v1.0.0        create
 *
 */
package com.wellbole.sms.client.service;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.wellbole.sms.client.SmsFetcher;
import com.wellbole.sms.client.Version;
import com.wellbole.sms.client.callback.InboundMessageFetchCallback;
import com.wellbole.sms.client.impl.DefaultInboundMessageReceivedCallback;
import com.wellbole.sms.client.message.InboundMessage;
import com.wellbole.sms.client.result.SmsFetchResult;

/**
 *
 * 短信接受线程服务，该服务定期主动获取上行短信，并回调客户提供的回调接口进行短信处理
 * @author 李飞
 *
 */
public class SmsFetcherThreadService implements Runnable,Service {
	/**
	 * 默认检查周期(3s)
	 */
	private final static int DEFAULT_PERIOD = 5;
	/**
	 * 日志
	 */
	private static final Logger logger = LogManager.getLogger(Thread.currentThread().getStackTrace()[2].getClassName());

	static{
		logger.info("SmsEngineClient version:"+Version.VERSION + ",update at:" + Version.LAST_UPDATE_AT);
	}

	/**
	 * 短信接受客户端
	 */
	private SmsFetcher smsFetcher = null;

	/**
	 * 上行短信接收处理回调接口
	 */
	private InboundMessageFetchCallback inboundMessageFetchCallback = null;

	/**
	 * 扩展代码，默认为空,取得该用户所有的上行短信，若不为空，则取得扩展码匹配的的上行短信。
	 */
	private String extCode = "";

	/**
	 * 上行短信检查周期（默认10秒种检查一次），单位秒
	 */
	private int period = DEFAULT_PERIOD;

	/**
	 * 调度线程池
	 */
	private ScheduledExecutorService scheduledExecutorService = Executors
			.newSingleThreadScheduledExecutor();

	/**
	 * 开始上行短信接受服务。
	 */
	public boolean start() {
		// 变量检查
		if (null == this.smsFetcher) {
			logger.error("smsReceiver is null!");
			return false;
		}
		if (null == this.inboundMessageFetchCallback) {
			logger.warn("notification is null!set it to DefaultInboundMessageCallback");
			this.inboundMessageFetchCallback = new DefaultInboundMessageReceivedCallback();

		}
		if (period < DEFAULT_PERIOD) {
			logger.warn("period is too short, set it to default value ："
					+ DEFAULT_PERIOD);
			period = DEFAULT_PERIOD;
		}
		scheduledExecutorService.scheduleAtFixedRate(this, 3, period,
				TimeUnit.SECONDS);
		logger.info("SmsReceiveThreadService is started!");
		return true;
	}

	/**
	 * 停止服务
	 */
	public void stop() {
		scheduledExecutorService.shutdown();
		logger.info("SmsReceiveThreadService is stoped!");
	}

	public void run() {
		// 取得上行短信
		SmsFetchResult receiveResult = this.smsFetcher.fetch(this.extCode);

		// 发生错误，记录错误信息
		if (receiveResult.hasError()) {
			logger.error(receiveResult.getErrorMessage());
			// 返回
			return;
		}
		//正确接收到数据
		if (receiveResult.hasData()) {
			logger.info("reveive InboundMessages: "
					+ receiveResult.getInboundMessageList().size());
			// 逐个回调
			for (InboundMessage msg : receiveResult.getInboundMessageList()) {
				// 回调处理上行短信
				this.inboundMessageFetchCallback.onFetch(msg);
			}
		}
	}

	/**
	 * 设定短信接受接口客户端。
	 *
	 * @param client
	 *            客户端。
	 */
	public final void setSmsFetcher(SmsFetcher smsFetcher) {
		this.smsFetcher = smsFetcher;
	}

	/**
	 * 设定上行短信通知接口实现类
	 *
	 * @param statusReportMessageFetchCallback
	 *            通知接口实现类
	 */
	public final void setInboundMessageFetchCallback(
			InboundMessageFetchCallback statusReportMessageFetchCallback) {
		this.inboundMessageFetchCallback = statusReportMessageFetchCallback;
	}

	/**
	 * 设定用户自定义扩展代码。若为空，取得该用户所有的上行短信，若不为空，则取得扩展码匹配的的上行短信。
	 * 假定系统分配给用户的扩展码为8888,设定扩展码为123，则查询扩展码为8888123的上行信息。
	 *
	 * @param extCode
	 *            自定义扩展代码
	 */
	public final void setExtCode(String extCode) {
		this.extCode = extCode;
	}

	/**
	 * 设定查询周期，每间隔多少秒查询一次服务器，默认10秒一次。
	 *
	 * @param period
	 *            查询周期，单位秒
	 */
	public final void setPeriod(int period) {
		this.period = period;
	}
}
